package face;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
 
/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		//获取人物信息
		String para = request.getParameter("imagebast64");
		String img = para.substring(para.lastIndexOf(",")+1);

		//人脸检查
		String result = FaceUtil.faceDetect(img);
		JSONObject jo = JSON.parseObject(result);
		//获取人脸数
		int faceNum = 0;
		if(jo.getJSONObject("result")!=null){
			faceNum = jo.getJSONObject("result").getIntValue("face_num");
		}
		//获取回调结果
		String rs = jo.getString("error_msg");
		//如果回到success并且人脸数为1
		if("SUCCESS".equals(rs) && faceNum==1){
			//在人脸库中搜索人脸
			result = FaceUtil.faceSearch(img);
			jo = JSON.parseObject(result).getJSONObject("result");
			int score = 0;
			if(jo != null){
				jo = jo.getJSONArray("user_list").getJSONObject(0);
				score = jo.getIntValue("score");
			}
			//判断人脸相似度，80%以上可以判定是同一个人
			if(score>=80){
				//获取用户userId
				String userId = jo.getString("user_id");
				//更新人脸库
				FaceUtil.faceUpdate(img, userId);
				//获取用户人脸列表
				FaceUtil.faceGetList(userId);

				response.getWriter().print(true);
			}else{
				response.getWriter().print(false);
			}
		}else{
			response.getWriter().print(false);
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request,response);
	}

}